var express = require('express');
var article = require('../models/article');
var label = require("../models/label");
var router = express.Router();

var jsonfyError=function(error){
  var message;
  if(error){
    message={
      code:0,
      msg:error.stack
    };
  }else{
    message={
      code:1,
      msg:"success"
    };
  }
  return message;
};

var showArticles = function (req, res, next) {

  article.list(function (error, articleList) {
    if (error) {
      throw new Error(error);
    } else {
      label.list(function(err,labelList){
        if(!err){
           res.render('articles', {
            articles: articleList,
            labels:labelList
          });
        }
      });
    }
  });
};

router.get('/', showArticles);

router.get('/articles', showArticles);

router.post('/articles', function (req, res, next) {
  var title = req.body.title;
  var content = req.body.content;
  var labelTexts = req.body.labels;

  article.save(title, content, function (error,data) {
    if (error) {
      throw new Error(error);
    } else {
      labelTexts.split(',').map(function(text){
        label.save(text,data.id,function(err){
          if(err){
            throw new Error(err);
          }
        });
      });
      res.redirect('/');
    }
  });
});

router.get('/articles/:id', function (req, res, next) {
  var id = req.params['id']

  article.get(id, function (error, data) {
    if (error) {
      throw new Error(error);
    } else {
      res.render('article', {
        article: data
      })
    }
  });

});

router.delete('/articles/:id', function (req, res, next) {
  var id = req.params['id'];

  article.delete(id, function (error) {
    res.json(jsonfyError(error));
  });
});

router.put('/articles/:id', function (req, res, next) {
  var id = req.params['id'];
  var title = req.body.title;
  var content = req.body.content;

  article.update(id, title, content, function (error) {
    res.json(jsonfyError(error));
  });

});

module.exports = router;
